﻿<template>
  <div class="etQuestion-container">
    <el-container>
      <el-aside width="250px" class="category-tree-aside">
        <category-tree
          v-model:bankId="queryParams.questionBankId"
          v-model:categoryId="queryParams.categoryId"
          @update:bankId="handleQuery"
          @update:categoryId="handleQuery"
        />
      </el-aside>

      <el-main class="question-list-main">
        <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
          <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="题目类型">
              <el-select v-model="queryParams.questionType" placeholder="请选择类型" clearable>
                <el-option 
                  v-for="(label, value) in questionTypeOptions" 
                  :key="value" 
                  :label="label" 
                  :value="value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable>
                <el-option 
                  v-for="(label, value) in difficultyOptions" 
                  :key="value" 
                  :label="label" 
                  :value="value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="关键词">
              <el-input v-model="queryParams.searchKey" placeholder="题目内容/标签" clearable />
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
                <el-button icon="ele-Refresh" @click="resetQuery">重置</el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Plus" @click="openAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="full-table" shadow="hover" style="margin-top: 8px">
          <el-table
            :data="tableData"
            style="width: 100%"
            v-loading="loading"
            border
            :height="tableHeight"
          >
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column prop="questionBankName" label="题库" min-width="120" show-overflow-tooltip />
            <el-table-column prop="categoryName" label="分类" min-width="120" show-overflow-tooltip />
            <el-table-column prop="content" label="题目内容" min-width="200" show-overflow-tooltip />
            <el-table-column prop="questionType" label="类型" width="100" align="center">
              <template #default="scope: { row: TableRow }">
                {{ questionTypeOptions[scope.row.questionType] }}
              </template>
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" width="80" align="center">
              <template #default="scope: { row: TableRow }">
                {{ difficultyOptions[scope.row.difficulty] }}
              </template>
            </el-table-column>
            <el-table-column prop="score" label="分数" width="80" align="center" />
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="scope">
                <el-button icon="ele-Edit" size="small" text type="primary" @click="openEdit(scope.row)">
                  编辑
                </el-button>
                <el-button icon="ele-Delete" size="small" text type="danger" @click="handleDelete(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:current-page="tableParams.page"
            v-model:page-size="tableParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="tableParams.total"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            size="default"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-main>
    </el-container>

    <!-- 编辑弹窗 -->
    <editDialog
      ref="editDialogRef"
      :title="editEtQuestionTitle"
      @reloadTable="handleQuery"
    />
  </div>
</template>

<script lang="ts" setup="" name="etQuestion">
  import { ref, onMounted } from 'vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { auth } from '/@/utils/authFunction';

  import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
  import { formatDate } from '/@/utils/formatTime';


  import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
  import editDialog from './component/editDialog.vue'
  import { pageEtQuestion, deleteEtQuestion } from '/@/api/main/et-question';
  import { getEtQuestionBankList } from '/@/api/main/et-question-bank';
  import { listEtQuestionCate } from '/@/api/main/et-question-cate';
  import CategoryTree from './component/categoryTree.vue';

  const showAdvanceQueryUI = ref(true);
  const printDialogRef = ref();
  const editDialogRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const queryParams = ref<any>({
    questionBankId: undefined,
    categoryId: undefined,
    questionType: undefined,
    difficulty: undefined,
    status: undefined,
    searchKey: ''
  });
  const tableParams = ref({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  const printEtQuestionTitle = ref("");
  const editEtQuestionTitle = ref("");

  // 改变高级查询的控件显示状态
  const changeAdvanceQueryUI = () => {
    showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
  }

  // 查询操作
  const handleQuery = async () => {
    try {
      loading.value = true;
      const res = await pageEtQuestion({
        ...queryParams.value,
        page: tableParams.value.page,
        pageSize: tableParams.value.pageSize
      });
      
      if (res.data.result) {
        tableData.value = res.data.result.items || [];
        tableParams.value.total = res.data.result.total;
      } else {
        tableData.value = [];
        tableParams.value.total = 0;
      }
    } catch (error) {
      console.error('查询失败:', error);
      ElMessage.error('查询失败');
      tableData.value = [];
      tableParams.value.total = 0;
    } finally {
      loading.value = false;
    }
  };

  // 列排序
  const sortChange = async (column: any) => {
	queryParams.value.field = column.prop;
	queryParams.value.order = column.order;
	await handleQuery();
  };

  // 打开新增页面
  const openAdd = () => {
    editEtQuestionTitle.value = '新增题目';
    if (editDialogRef.value) {
      editDialogRef.value.openDialog({
        orderNo: 100,
        status: 1,
        questionType: 1,
        difficulty: 1,
        score: 1
      });
    }
  };

  // 打开打印页面
  const openPrintEtQuestion = async (row: any) => {
    printEtQuestionTitle.value = '打印题目管理';
  }
  
  // 打开编辑页面
  const openEdit = (row: any) => {
    editEtQuestionTitle.value = '编辑题目';
    if (editDialogRef.value) {
      editDialogRef.value.openDialog(row);
    }
  };

  // 删除
  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除该题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      
      await deleteEtQuestion({ id: row.id });
      ElMessage.success('删除成功');
      handleQuery();
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
      }
    }
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

  // 定义类型
  interface QuestionBank {
    id: number;
    name: string;
  }

  interface QuestionCategory {
    id: number;
    name: string;
    children?: QuestionCategory[];
  }

  // 修改 ref 定义
  const bankOptions = ref<QuestionBank[]>([]);
  const categoryOptions = ref<QuestionCategory[]>([]);
  const tableHeight = ref(window.innerHeight - 300);

  // 修改 scope 类型
  interface TableRow {
    questionType: keyof typeof questionTypeOptions;
    difficulty: keyof typeof difficultyOptions;
    // ... 其他字段
  }

  // 编辑弹窗
  const editTitle = ref('');

  // 获取题库列表
  const getBankOptions = async () => {
    try {
      const res = await getEtQuestionBankList();
      bankOptions.value = res.data.result || [];
    } catch (error) {
      console.error('获取题库列表失败:', error);
      ElMessage.error('获取题库列表失败');
    }
  };

  // 获取分类列表
  const getCategoryOptions = async () => {
    try {
      const res = await listEtQuestionCate({ 
        questionBankId: queryParams.value.questionBankId 
      });
      categoryOptions.value = res.data.result || [];
    } catch (error) {
      console.error('获取分类列表失败:', error);
      ElMessage.error('获取分类列表失败');
    }
  };

  // 重置查询
  const resetQuery = () => {
    queryParams.value = {
      questionBankId: undefined,
      categoryId: undefined,
      questionType: undefined,
      difficulty: undefined,
      status: undefined,
      searchKey: ''
    };
    handleQuery();
  };

  // 定义题目类型选项
  const questionTypeOptions: Record<number, string> = {
    1: '判断题',
    2: '单选题',
    3: '多选题',
    4: '填空题',
    5: '简答题',
    6: '组合题',
    7: '编程题',
    8: '实操题'
  } as const;

  // 定义难度选项
  const difficultyOptions: Record<number, string> = {
    1: '简单',
    2: '中等',
    3: '困难'
  } as const;

  // 初始化
  onMounted(async () => {
    await getBankOptions();
    if (bankOptions.value.length > 0) {
      queryParams.value.questionBankId = bankOptions.value[0].id;
      await getCategoryOptions();
    }
    handleQuery();
  });
</script>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>

<style lang="scss" scoped>
.etQuestion-container {
  height: 100%;
  
  .el-container {
    height: 100%;
  }

  .category-tree-aside {
    padding-right: 8px;
    
    .category-tree-card {
      height: 100%;
      
      :deep(.el-card__header) {
        padding: 10px;
      }
      
      .card-header {
        display: flex;
        flex-direction: column;
        gap: 8px;
        
        .el-select {
          width: 100%;
        }
      }
    }
  }

  .question-list-main {
    padding: 0;
  }
}
</style>

